import axios from 'axios';

async function get<T>(api: string) { 
  let res = await axios.get<T>(api);
  return res.data.data;
}
async function post<T>(api: string, data: any) {
  let res = await axios.post<T>(api, data);
  let dd = res.data;
  if(!data.page) return dd.data;
  if(!dd.data || !dd.data.length) {
    return {totalCount:0,items:[]}
  }
  return {totalCount:dd.pageMeta.totalCount,items:dd.data};
}

async function requestPost<T>(api: string, data: any) {
  let res = await axios.post<T>(api, data);
  let dd = res.data;
  return dd.data;
}

async function put<T>(api: string, data: any) {
  let res = await axios.put<T>(api, data);
  return res.data.data;
}
async function del(api: string) {
  let res = await axios.delete(api);
  return res.data.data;
}
async function DownFile<T>(api: string, data: any) { 
  return axios({
    url: api,
    method: 'post',
    responseType: 'blob'
  })
}

export default {
  get,
  post,
  requestPost,
  put,
  del,
  DownFile,
}
export interface ListResult {
  totalCount: number;
  items: Array<any>;
}

export function toOptions(data:Array<any>, label:string, value:string) {
  return (data||[]).map(a=>{
    return {
      label: a[label],
      value: a[value]
    };
  });
}

export function getQuery(idName:string) {
  return {
    "page": 1,
    "pageSize": 1000,
    "sortProperty": idName,
    "sortDirection": "Asc",
    "queryProperties": []
  }
}